// test project main.go
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"test/conf"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

type finfo struct {
	name string
	time int64
	path string
}

var arr []finfo

func walkfunc(path string, info os.FileInfo, err error) error {
	if !info.IsDir() {
		arr = append(arr, finfo{name: info.Name(), time: info.ModTime().Unix(), path: path})
	}
	return nil
}

func typeof(v interface{}) string {
	return fmt.Sprintf("%T", v)
}

func handleError(err error) {
	fmt.Println("Error:", err)
	os.Exit(-1)
}

type OssProgressListener struct {
}

func (listener *OssProgressListener) ProgressChanged(event *oss.ProgressEvent) {
	switch event.EventType {
	case oss.TransferStartedEvent:
		fmt.Printf(" uploadStart, size: %d, TotalBytes %d.\n",
			event.ConsumedBytes, event.TotalBytes)
	case oss.TransferDataEvent:
		fmt.Printf("\r upload, size: %d, TotalBytes %d, %d%%. \r",
			event.ConsumedBytes, event.TotalBytes, event.ConsumedBytes*100/event.TotalBytes)
	case oss.TransferCompletedEvent:
		fmt.Printf("\n uploadEnd, size: %d, TotalBytes %d.\n",
			event.ConsumedBytes, event.TotalBytes)
	case oss.TransferFailedEvent:
		fmt.Printf("\n uploadErr, size: %d, TotalBytes %d.\n",
			event.ConsumedBytes, event.TotalBytes)
	default:
	}
}

func alioss(filename string, filepath string) {
	endpoint := "http://oss-cn-beijing.aliyuncs.com"
	accessKeyId := "LTAIIPUeyJdK3bBI"
	accessKeySecret := "JlF1WcEvU2yKNcRzx7xGPelHtFpZIC"
	bucketName := "chunshantest"

	client, err := oss.New(endpoint, accessKeyId, accessKeySecret)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	err = bucket.PutObjectFromFile(filename, filepath, oss.Progress(&OssProgressListener{}))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
}
func maopao(arr []finfo) []finfo {
	num := len(arr)
	for i := 0; i < num; i++ {
		for j := i + 1; j < num; j++ {
			if arr[i].time < arr[j].time {
				tmp := arr[i]
				arr[i] = arr[j]
				arr[j] = tmp
			}
		}
	}
	return arr
}

func main() {
	arg_num := len(os.Args)
	if arg_num <= 2 {
		fmt.Print("请输入 命令 本地地址 远程文件地址 【例如 命令 上传的文件目录地址 阿里云线上地址目录 （不要将此文件放在上传目录同级）】\r\n")
		return
	}
	path := os.Args[1]  //本地文件夹地址
	cname := os.Args[2] //类型 work_file

	flll, err := os.Stat(string(path))
	if err != nil {
		fmt.Print(path)
		fmt.Print("dir error")
		return
	} else {
		if !flll.IsDir() {
			fmt.Print("dir error")
			return
		}
	}

	//	F:\\aa

	fmt.Print("start get files list \r\n")

	filepath.Walk(string(path), walkfunc)
	fmt.Print("sort files list \r\n")
	arr = maopao(arr)
	fmt.Print("list get end \r\n")
	fi := conf.Gtcf(string(cname))

	if fi != "false" {
		a := strings.Split(fi, "\r\n")

		the_time, err := time.ParseInLocation("2006-01-02 15:04:05", a[1], time.Local)
		var unix_time int64
		if err == nil {
			unix_time = the_time.Unix()
		} else {
			return
		}
		starttime := unix_time

		startkey := -1
		for key := range arr {
			if arr[key].time < starttime {
				startkey = key
				break
			}
		}
		if startkey == -1 {
			fmt.Print("\r\n ======》 no file is upload")
			return
		}
		newarr := arr[startkey:]
		fmt.Print("【read config Continue】,\r\n")
		fmt.Print(arr[startkey].time, "--", starttime, a[0])

		for k := range newarr {
			fmt.Print("\r\n Ready to upload", newarr[k].name, "\r\n")
			alioss(cname+"/"+newarr[k].name, newarr[k].path)
			conf.Gtc(string(cname), newarr[k].name, newarr[k].time, newarr[k].path)
			fmt.Print("【config update】\r\n", newarr[k].name, newarr[k].time, newarr[k].path)

		}
		fmt.Print("\r\nEND\r\n")

	} else {
		fmt.Print("【no config  Start from zero】,\r\n")
		newarr := arr[0:]

		for k := range newarr {
			fmt.Print("\r\n Ready to upload", newarr[k].name, "\r\n")
			alioss(cname+"/"+newarr[k].name, newarr[k].path)
			conf.Gtc(string(cname), newarr[k].name, newarr[k].time, newarr[k].path)
			fmt.Print("【config update】\r\n")

		}
		fmt.Print("\r\n END\r\n")

	}

}
